#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define SHM_SIZE 1024

int main() {
    int shmid;
    pid_t pid;
    char *shm_addr;

    // 1. 创建共享内存
    if ((shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT | 0666)) < 0) {
        perror("shmget failed");
        exit(EXIT_FAILURE);
    }

    // 2. 创建子进程
    pid = fork();
    if (pid < 0) {
        perror("fork failed");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) { // 子进程（读取数据）
        // 映射共享内存
        shm_addr = (char *)shmat(shmid, NULL, 0);
        if (shm_addr == (char *)-1) {
            perror("shmat failed");
            exit(EXIT_FAILURE);
        }

        // 等待父进程写入数据
        sleep(1); // 简单同步
        
        printf("Child received: %s\n", shm_addr);

        // 解除映射
        shmdt(shm_addr);
        exit(EXIT_SUCCESS);

    } else { // 父进程（写入数据）
        // 映射共享内存
        shm_addr = (char *)shmat(shmid, NULL, 0);
        if (shm_addr == (char *)-1) {
            perror("shmat failed");
            exit(EXIT_FAILURE);
        }

        // 写入数据
        strcpy(shm_addr, "Hello Shared Memory!");
        printf("Parent wrote: %s\n", shm_addr);

        // 等待子进程完成
        wait(NULL);

        // 清理资源
        shmdt(shm_addr);
        shmctl(shmid, IPC_RMID, NULL);
    }

    return 0;
}
